<script setup lang="ts">
import { computed, reactive, ref } from "vue";
import {
  onLoad,
  onPullDownRefresh,
  onReachBottom,
  onUnload,
} from "@dcloudio/uni-app";
import { useQuery } from "@/hooks/init";
import { useShare } from "@/hooks/share";
import { usePageScroll } from "@/hooks/scroll";
import { useList } from "@/hooks/page";
import {
  community_index_api,
  community_note_list_api,
} from "@/api/guider_home";
import { note_info_api, common_like_api } from "@/api/guider_didi";
import { data_api } from "@/api/my";
import { EV_LOGIN, EV_NOTE } from "@/constant/event";
import { Account } from "@/utils/account";
import { AppData } from "@/utils/app";
import { Window } from "@/utils/window";
import { createWaterfall } from "@/utils/waterfall";
import { Router } from "@/utils/router";

import NavBar from "@/components/nav/bar.vue";
import NavBg from "@/components/nav/bg.vue";
import NavSpace from "@/components/nav/space.vue";
import Swipe from "@/components/swipe/swipe.vue";
import SwipeDot from "@/components/swipe/dot.vue";
import IndexMenuTitle from "./components/index-menu-title.vue";
import IndexMoreBtn from "./components/index-more-btn.vue";
import CommunityInterviewItem from "./components/community-interview-item.vue";
import CommunityGroupItem from "./components/community-group-item.vue";
import PageSticky from "@/components/page/sticky.vue";
import CommunityTypeItem from "./components/community-type-item.vue";
import CommunityNoteItem from "./components/community-note-item.vue";
import CommunityNoteLike from "./components/community-note-like.vue";
import ListMore from "@/components/list/more.vue";
import CommunityNoteBtn from "./components/community-note-btn.vue";
import CommunityNotePicker from "./components/community-note-picker.vue";
import PopupModal from "@/components/popup/modal.vue";

onLoad((options) => {
  useQuery(options as MiniApp.AppLaunchOption, () => {
    reloadData();

    AppData.initConfig((config) => {
      shareOption.title = config.share_info.title;
    });

    Account.isLogin && reloadMyData();
    uni.$on(EV_LOGIN, evLoginCallback);
    uni.$on(EV_NOTE, evNoteCallback);
  });
});
onPullDownRefresh(() => {
  reloadData()
    .then(() => uni.stopPullDownRefresh())
    .catch(() => uni.stopPullDownRefresh());
});
const { pageIsScroll, onPageScroll } = usePageScroll(() => {
  listLoadMore.value = listData.value.length > 1;
});
onReachBottom(() => loadMoreList());
onUnload(() => {
  uni.$off(EV_LOGIN, evLoginCallback);
  uni.$off(EV_NOTE, evNoteCallback);
});

const reloadData = () => {
  return community_index_api().then((resp) => {
    adList.value = resp.banner;

    const guider_interview = resp.menu_title.find(
      (i) => i.key === "guider_interview"
    );
    if (guider_interview) {
      interviewData.title = guider_interview.show_title;
      interviewData.desc = guider_interview.sub_title;
    }
    interviewList.value = resp.guider_interview;

    const hot_group = resp.menu_title.find((i) => i.key === "hot_group");
    if (hot_group) {
      groupData.title = hot_group.show_title;
      groupData.desc = hot_group.sub_title;
    }
    groupList.value = resp.hot_group;

    const guider_share = resp.menu_title.find((i) => i.key === "guider_share");
    if (guider_share) {
      noteData.title = guider_share.show_title;
      noteData.desc = guider_share.sub_title;
    }
    noteTypeList.value = resp.guider_share;
    if (resp.guider_share.length > 1) noteTypeClick(resp.guider_share[0].id);
  });
};

const adIndex = ref(0);
const adList = ref<any[]>([]);
const adClick = () => {
  const ad = adList.value[adIndex.value];
  ad.url.startsWith("http")
    ? Router.navigateToWeb(ad.url, "1")
    : Router.navigateTo(ad.url);
};

const interviewData = reactive({ title: "名导访谈", desc: "" });
const interviewList = ref<any[]>([]);
const interviewClick = (id: string) => {
  id
    ? Router.navigateTo(`/package/famous-talk/pages/detail/index?id=${id}`)
    : Router.navigateTo(`/package/famous-talk/pages/guider/index`);
};

const groupData = reactive({ title: "热门社群", desc: "" });
const groupList = ref<any[]>([]);
const groupClick = (id: string) => {
  checkCertificate((isLogin) => {
    Router.navigateToOrRedirectTo(
      isLogin,
      id
        ? `/package/community/pages/group/detail?id=${id}`
        : `/package/community/pages/group/index`
    );
  });
};

const noteTypeList = ref<any[]>([]);
const noteTypeClick = (id: string) => {
  queryData.cate_id = id;
  reloadList();
};

const noteData = reactive({ title: "分享汇", desc: "" });
const noteList = computed(() => {
  return createWaterfall(
    listData.value.map((i) => {
      if (i.type === 3) {
        Object.assign(i, { img_width: 200, img_height: 290 });
      }
      return i;
    }),
    {
      baseWidth: Window.rpxToPx(336),
      columnHeight: [0, 0],
      widthKey: "img_width",
      heightKey: "img_height",
    }
  );
});
const noteClick = (index: number, index2: number) => {
  if (index === -1) {
    Account.checkLogin((isLogin) => {
      isLogin && Router.navigateBack();
      communityNotePicker.value?.show((type, filePath) => {
        Router.navigateTo(
          `/package/guider/pages/note/edit?${Router.dataToQuery({
            type,
            filePath,
          })}`
        );
      });
    });
  } else {
    const note = noteList.value.columnData[index][index2] as any;
    Router.navigateTo(
      note.type === 2
        ? `/package/guider/pages/note/detail2?id=${note.id}`
        : `/package/guider/pages/note/detail?id=${note.id}`
    );
  }
};

const queryData = { cate_id: "" };
const { listData, listStatus, listLoadMore, reloadList, loadMoreList } =
  useList({ page: 1, page_size: 10 }, (query) => {
    return community_note_list_api({ ...query, ...queryData });
  });

const checkCertificate = (callback: (isLogin: boolean) => void) => {
  Account.checkLogin((isLogin) => {
    // 已认证
    if (AppData.userData.is_guide_certification === 1) return callback(isLogin);

    isLogin && Router.navigateBack();
    popupModal.value?.show(
      {
        content:
          "你好！这里是全球导游人的家园，为了能给你提供针对性的专业内容服务，需要对你身份进行基础认证，敬请理解！",
        confirmText: "开始认证",
        translateY: "-55%",
      },
      () => {
        Router.navigateTo(
          AppData.userData.status === -1
            ? "/package/guider/pages/apply/type"
            : "/package/guider/pages/apply/detail"
        );
      }
    );
  });
};

const myDataLikeList = ref<number[]>([]);
const likeClick = (id: number) => {
  const fn = () => {
    const index = myDataLikeList.value.indexOf(id);
    index === -1
      ? myDataLikeList.value.push(id)
      : myDataLikeList.value.splice(index, 1);
    common_like_api({ id, type: 2 }).then(() => {
      uni.$emit(EV_NOTE, { type: "like", data: { type: "guider", id } });
    });
  };

  Account.isLogin
    ? fn()
    : Account.login(() => {
        reloadMyData().then(() => {
          // 没有点赞，则点赞
          myDataLikeList.value.includes(id) || fn();
        });
        Router.navigateBack();
      });
};

const reloadMyData = () => {
  return data_api<{ guide_share_note_like?: number[] }>({
    includes: "guide_share_note_like",
  }).then((resp) => {
    myDataLikeList.value = resp.guide_share_note_like || [];
  });
};
const evLoginCallback = (e: { type: "cancel" }) => {
  console.info(`触发事件：${EV_LOGIN}`, e);
  e.type === "cancel" || reloadMyData();
};
const evNoteCallback = (e: {
  type: "like";
  data: { type: "guider"; id: number };
}) => {
  console.info(`触发事件：${EV_NOTE}`, e);
  if (e.type === "like" && e.data.type === "guider") {
    // 刷新状态
    reloadMyData();
    // 刷新数字
    note_info_api({ id: `${e.data.id}` }).then((resp) => {
      const index = listData.value.findIndex((i) => i.id === resp.id);
      listData.value[index].like_count_str = resp.like_count_str;
    });
  }
};

const communityNotePicker = ref<InstanceType<typeof CommunityNotePicker>>();
const popupModal = ref<InstanceType<typeof PopupModal>>();

const { onShareAppMessage, onShareTimeline, shareOption } = useShare(
  "/pages/index/community"
);
</script>

<template>
  <NavBar title="社区" />
  <NavBg :retract="pageIsScroll" url="/static/index-bg.png" />
  <NavSpace />

  <view class="community-ad">
    <view class="community-ad-bg"></view>
    <view class="community-ad-swipe" @click="adClick">
      <Swipe v-model="adIndex" :listData="adList" labelKey="img_url" autoplay />
    </view>
    <view class="community-ad-dot">
      <SwipeDot v-model="adIndex" :total="adList.length" />
    </view>
  </view>

  <view class="community-interview">
    <view class="community-interview-head">
      <IndexMenuTitle :title="interviewData.title" />
      <view class="community-interview-more" @click="interviewClick('')">
        <IndexMoreBtn />
      </view>
    </view>
    <view class="community-interview-desc">{{ interviewData.desc }}</view>
    <view class="community-interview-wrapper">
      <view
        class="community-interview-item"
        :style="{ width: d / 3 === 0 ? '690rpx' : '' }"
        v-for="(i, d) of interviewList"
        :key="i.id"
        @click="interviewClick(i.id)"
      >
        <CommunityInterviewItem :info="i" :isLarge="d / 3 === 0" />
      </view>
    </view>
  </view>

  <view class="community-group">
    <view class="community-group-head">
      <IndexMenuTitle :title="groupData.title" />
      <view class="community-group-more" @click="groupClick('')">
        <IndexMoreBtn />
      </view>
    </view>
    <view class="community-group-desc">{{ groupData.desc }}</view>
    <view class="community-group-wrapper">
      <view
        class="community-group-item"
        v-for="i of groupList"
        :key="i.id"
        @click="groupClick(i.id)"
      >
        <CommunityGroupItem :info="i" />
      </view>
    </view>
  </view>

  <view class="community-note">
    <view class="community-note-head">
      <IndexMenuTitle :title="noteData.title" />
    </view>
    <view class="community-note-desc">{{ noteData.desc }}</view>
    <PageSticky customNav background="#f9f9f9">
      <scroll-view
        class="community-note-type"
        scroll-x
        enhanced
        :show-scrollbar="false"
      >
        <view class="community-note-type2"></view>
        <view
          class="community-note-type3"
          v-for="i of noteTypeList"
          :key="i.id"
          @click="noteTypeClick(i.id)"
        >
          <CommunityTypeItem
            :isActive="queryData.cate_id === i.id"
            :text="i.name"
          />
        </view>
      </scroll-view>
    </PageSticky>

    <view class="community-note-wrapper">
      <view
        class="community-note-column"
        v-for="(i, d) of noteList.columnData"
        :key="d"
        :style="{ width: `${noteList.columnWidth}px` }"
      >
        <view
          class="community-note-item"
          v-for="(j, x) of i"
          :key="j.id"
          @click="noteClick(d, x)"
        >
          <CommunityNoteItem :info="j">
            <view class="community-note-like" @click.stop="likeClick(j.id)">
              <CommunityNoteLike
                :text="j.like_count_str"
                :isLike="myDataLikeList.includes(j.id)"
              />
            </view>
          </CommunityNoteItem>
        </view>
      </view>
    </view>
    <ListMore v-if="listLoadMore" :status="listStatus" />

    <view class="community-note-add" @click="noteClick(-1)">
      <CommunityNoteBtn />
    </view>
  </view>

  <CommunityNotePicker ref="communityNotePicker" />
  <PopupModal ref="popupModal" />
</template>

<style lang="scss">
page {
  padding-top: 30rpx;
  padding-bottom: 160rpx;
}

.community-ad {
  position: relative;
  margin: 0 40rpx 52rpx;

  .community-ad-bg {
    position: absolute;
    left: 20rpx;
    top: 18rpx;
    right: 20rpx;
    height: 244rpx;
    border-radius: 20rpx;
    background-color: rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(20rpx);
  }

  .community-ad-swipe {
    position: relative;
    height: 250rpx;
    border-radius: 20rpx;
    overflow: hidden;
  }

  .community-ad-dot {
    position: absolute;
    right: 30rpx;
    bottom: 20rpx;
  }
}

.community-interview {
  position: relative;
  margin-bottom: 20rpx;

  .community-interview-head {
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    margin-bottom: 12rpx;
  }

  .community-interview-more {
    margin-left: auto;
  }

  .community-interview-desc {
    padding-left: 30rpx;
    margin-bottom: 20rpx;
    font-size: 26rpx;
    color: #999999;
    line-height: 36rpx;
  }

  .community-interview-wrapper {
    display: flex;
    flex-wrap: wrap;
    padding-left: 30rpx;
    padding-bottom: 20rpx;
  }

  .community-interview-item {
    width: 336rpx;
    margin-right: 18rpx;
    margin-bottom: 20rpx;
  }
}

.community-group {
  position: relative;
  margin-bottom: 60rpx;

  .community-group-head {
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    margin-bottom: 12rpx;
  }

  .community-group-more {
    margin-left: auto;
  }

  .community-group-desc {
    padding-left: 30rpx;
    margin-bottom: 20rpx;
    font-size: 26rpx;
    color: #999999;
    line-height: 36rpx;
  }

  .community-group-wrapper {
    display: flex;
    flex-wrap: wrap;
    padding: 4rpx 10rpx;
    margin: 0 30rpx;
    border-radius: 22rpx;
    background-color: #ffffff;
  }

  .community-group-item {
    width: 50%;
    padding: 16rpx 10rpx;
    box-sizing: border-box;
  }
}

.community-note {
  .community-note-head {
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    margin-bottom: 12rpx;
  }

  .community-note-desc {
    padding-left: 30rpx;
    margin-bottom: 10rpx;
    font-size: 26rpx;
    color: #999999;
    line-height: 36rpx;
  }

  .community-note-type {
    height: 88rpx;
    white-space: nowrap;
  }

  .community-note-type2,
  .community-note-type3 {
    display: inline-block;
    vertical-align: top;
  }

  .community-note-type2 {
    width: 30rpx;
  }

  .community-note-type3 {
    margin-top: 16rpx;
    margin-right: 20rpx;
  }

  .community-note-wrapper {
    display: flex;
    justify-content: flex-start;
    padding-left: 30rpx;
    padding-top: 10rpx;
    padding-bottom: 1rpx;
  }

  .community-note-column {
    margin-right: 18rpx;
  }

  .community-note-item {
    margin-bottom: 20rpx;
  }

  .community-note-like {
    flex-shrink: 0;
    margin-left: 10rpx;
  }

  .community-note-add {
    position: fixed;
    left: 50%;
    bottom: 60rpx;
    transform: translateX(-50%);
  }
}
</style>